<script setup lang="ts">

import {useRoute, useRouter} from "vue-router";
import {ref} from "vue";
import myAxios from "../plugins/myAxios.ts";
import {Toast} from "vant";
import {getCurrentUser} from "../services/user.ts";

const route = useRoute();
const router = useRouter();
const editUser = ref({
  editKey : route.query.editKey,
  editName: route.query.editName,
  currentValue: route.query.currentValue
})


const onSubmit = async () => {
  const currentUser = await getCurrentUser();
  const res = await myAxios.post('/user/update',{
    'id': currentUser.id,
    [editUser.value.editKey as string]:editUser.value.currentValue
  })

  console.log("修改用户",res);

  if (!(res.code === 0 && res.data)) {
    Toast.fail('修改失败')
  } else {
    Toast.success('修改成功');
    localStorage.removeItem('currentUser');
    const updateUser = await getCurrentUser();
    localStorage.setItem('currentUser',JSON.stringify(updateUser))
    router.back();
  }
};

const avatarFile = ref()

const ImgUploadFile = async (params: any) => {
  // 要把数据变成file格式
  const formData = new FormData(); // 下面有备注
  formData.append('file', params);
  console.log(formData)
  return await myAxios.post('/file/upload', formData, {
    headers: {
      // 注意修改请求头file格式
      'Content-Type': 'multipart/form-data',
    },
  });
};

const afterRead = async (file : any) => {
  // 返回图片信息
  console.log(file);
  const uploadUrl = await ImgUploadFile(file.file)
  if(uploadUrl.data){
    console.log("uploadUrl",uploadUrl.data);
    editUser.value.currentValue =  uploadUrl.data.fileName;
  }else {
    Toast.fail('上传失败')
  }

};

</script>

<template>
  <van-form @submit="onSubmit">
      <van-field  v-if="editUser.editKey!=='avatarUrl'"
          :v-model="editUser.currentValue"
          :name="editUser.editKey as string"
          :label="editUser.editName as string"
          :placeholder="`请输入${editUser.editName}`"
      />

    <div v-if="editUser.editKey==='avatarUrl'" style="display: flex;justify-content: center;">
      <van-field name="uploader" label="头像上传">
        <template #input>
          <van-uploader	 v-model="avatarFile" max-count="1" upload-text="上传头像" :after-read="afterRead"  />
        </template>
      </van-field>
    </div>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<style scoped>

</style>